import PureEnvironmentList from '../components/environment-list.jsx';
import {fetchEnvironmentList,createEnvironment,removeEnvironment,updateEnvironment} from 'actions/environment';
import { getFetchStatus } from 'actions/util';
import * as ReactRedux from 'react-redux';
import * as React from 'react';

const mapStateToProps = (state) => {
  return {
    isFetching: getFetchStatus(state, fetchEnvironmentList),
    environmentList: state.environmentList
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    initFetch: () => {
      dispatch(fetchEnvironmentList());
    },
    onEnvironmentSave: (environment) => {
      var data;
      if (environment.id) {
        data = updateEnvironment(environment)
      } else {
        data = createEnvironment(environment)
      }
      return dispatch(data)
        .then(()=>dispatch(fetchEnvironmentList()));
    },
    onEnvironmentRemove: (environmentId) => {
      return dispatch(removeEnvironment(environmentId))
        .then(()=>dispatch(fetchEnvironmentList()));
    },
  };
};

class EnvironmentList extends React.Component {
  componentDidMount() {
    this.props.initFetch();
  }

  render() {
    return <PureEnvironmentList {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(EnvironmentList);
